<template>
  <div class="dish-page">
    <div class="page-header">
      <div class="title">菜品管理</div>
      <div class="desc">管理餐厅的所有菜品和口味</div>
    </div>

    <div class="content-card">
      <div class="search-bar">
        <div class="search-item">
          <span>菜品名称：</span>
          <el-input
            v-model="searchQuery.name"
            placeholder="请输入菜品名称"
            class="search-input"
            clearable
          >
          </el-input>
        </div>
        <div class="search-item">
          <span>菜品分类：</span>
          <el-select v-model="searchQuery.categoryId" placeholder="请选择" clearable class="type-select">
            <el-option label="全部" :value="null" />
            <el-option 
              v-for="item in categoryList" 
              :key="item.id" 
              :label="item.name" 
              :value="item.id" 
            />
          </el-select>
        </div>
        <div class="search-item">
          <span>状态：</span>
          <el-select v-model="searchQuery.status" placeholder="请选择" clearable class="status-select">
            <el-option label="全部" :value="null" />
            <el-option label="起售" :value="1" />
            <el-option label="停售" :value="0" />
          </el-select>
        </div>
        <el-button type="primary" @click="handleSearch" class="search-btn">
          查询
        </el-button>
        <el-button type="info" @click="handleReset" class="refresh-btn">
          <el-icon><RefreshRight /></el-icon>
          重置
        </el-button>
        <el-button type="primary" @click="handleAdd" class="add-btn">
          + 新增菜品
        </el-button>
        <el-button type="danger" @click="handleBatchDelete" class="batch-delete-btn" :disabled="selectedIds.length === 0">
          批量删除
        </el-button>
      </div>

      <el-table 
        :data="dishList" 
        border 
        style="width: 100%" 
        v-loading="loading"
        :header-cell-style="{background:'#f8f8f9', color: '#333', fontWeight: 'bold'}"
        :row-class-name="tableRowClassName"
        highlight-current-row
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="name" label="菜品名称" min-width="120">
          <template #default="{row}">
            <div class="dish-info">
              <el-image
                v-if="row.image"
                :src="row.image"
                class="dish-image"
                :preview-src-list="[row.image]"
              />
              <span class="dish-name">{{ row.name }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="categoryName" label="分类" width="120" align="center" />
        <el-table-column prop="price" label="售价" width="120" align="center">
          <template #default="{row}">
            <span>￥{{ parseFloat(row.price).toFixed(2) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="售卖状态" width="100" align="center">
          <template #default="{ row }">
            <el-switch
              v-model="row.status"
              :active-value="1"
              :inactive-value="0"
              @change="handleStatusChange(row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="最后操作时间" min-width="160">
          <template #default="{row}">
            <div class="time-info">
              <el-icon><Timer /></el-icon>
              <span>{{ row.updateTime }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="220" align="center">
          <template #default="{ row }">
            <div class="operation-btns">
              <el-tooltip content="编辑菜品" placement="top" :show-after="300">
                <el-button type="primary" link @click="handleEdit(row)" class="op-button">
                  <el-icon><Edit /></el-icon>
                  <span>修改</span>
                </el-button>
              </el-tooltip>
              <el-divider direction="vertical" />
              <el-tooltip :content="row.status === 1 ? '停售菜品' : '起售菜品'" placement="top" :show-after="300">
                <el-button 
                  type="primary" 
                  link 
                  :class="row.status === 1 ? 'op-button-warning' : 'op-button-success'"
                  @click="handleToggleStatus(row)"
                >
                  <el-icon>
                    <VideoPause v-if="row.status === 1" />
                    <VideoPlay v-else />
                  </el-icon>
                  <span>{{ row.status === 1 ? '停售' : '起售' }}</span>
                </el-button>
              </el-tooltip>
              <el-divider direction="vertical" />
              <el-tooltip content="删除菜品" placement="top" :show-after="300">
                <el-button 
                  type="primary" 
                  link 
                  class="op-button-danger"
                  @click="handleDelete(row)"
                >
                  <el-icon><Delete /></el-icon>
                  <span>删除</span>
                </el-button>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <span>共 {{ total }} 条</span>
        <el-select v-model="pageSize" class="page-size-select" @change="handleSizeChange">
          <el-option :value="10" label="10条/页" />
          <el-option :value="20" label="20条/页" />
          <el-option :value="30" label="30条/页" />
          <el-option :value="40" label="40条/页" />
        </el-select>
        <el-pagination
          layout="prev, pager, next"
          :current-page="currentPage"
          :page-size="pageSize"
          :total="total"
          @current-change="handleCurrentChange"
          background
        />
        <span>前往 <el-input v-model="jumpPage" class="jump-page" @keyup.enter="handleJumpPage" /> 页</span>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import dishApi from '@/api/dish'
import categoryApi from '@/api/category'
import { 
  Edit, 
  Delete, 
  RefreshRight, 
  Timer, 
  VideoPlay, 
  VideoPause 
} from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'

const router = useRouter()

// 菜品列表数据
const dishList = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const jumpPage = ref('')
const loading = ref(false)
const categoryList = ref([])
const selectedIds = ref([])

// 搜索条件
const searchQuery = reactive({
  name: '',
  categoryId: null,
  status: null
})

// 获取菜品列表
const getDishList = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value
    }
    
    // 添加搜索条件
    if (searchQuery.name) {
      params.name = searchQuery.name
    }
    if (searchQuery.categoryId) {
      params.categoryId = searchQuery.categoryId
    }
    if (searchQuery.status !== null) {
      params.status = searchQuery.status
    }
    
    const res = await dishApi.getDishPage(params)
    if (res.code === 1) {
      dishList.value = res.data.records || []
      total.value = res.data.total || 0
    }
  } catch (error) {
    console.error('获取菜品列表失败:', error)
    ElMessage.error('获取菜品列表失败')
  } finally {
    loading.value = false
  }
}

// 获取分类列表
const getCategoryList = async () => {
  try {
    // 只获取菜品分类（type=1）
    const res = await categoryApi.getCategoryList(1)
    if (res.code === 1) {
      categoryList.value = res.data || []
    }
  } catch (error) {
    console.error('获取分类列表失败:', error)
    ElMessage.error('获取分类列表失败')
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  getDishList()
}

// 重置搜索条件
const handleReset = () => {
  searchQuery.name = ''
  searchQuery.categoryId = null
  searchQuery.status = null
  currentPage.value = 1
  getDishList()
}

// 添加菜品
const handleAdd = () => {
  router.push('/dish/add')
}

// 编辑菜品
const handleEdit = (row) => {
  router.push(`/dish/edit/${row.id}`)
}

// 删除菜品
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除「${row.name}」菜品吗？`,
    '删除菜品',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const res = await dishApi.deleteDish([row.id])
      if (res.code === 1) {
        ElMessage.success('删除成功')
        getDishList()
      }
    } catch (error) {
      console.error('删除菜品失败:', error)
      ElMessage.error('删除菜品失败')
    }
  }).catch(() => {})
}

// 批量删除菜品
const handleBatchDelete = () => {
  if (selectedIds.value.length === 0) return
  
  ElMessageBox.confirm(
    `确定要删除选中的 ${selectedIds.value.length} 个菜品吗？`,
    '批量删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const res = await dishApi.deleteDish(selectedIds.value)
      if (res.code === 1) {
        ElMessage.success('批量删除成功')
        getDishList()
      }
    } catch (error) {
      console.error('批量删除菜品失败:', error)
      ElMessage.error('批量删除菜品失败')
    }
  }).catch(() => {})
}

// 起售/停售菜品
const handleToggleStatus = (row) => {
  const statusText = row.status === 1 ? '停售' : '起售'
  const newStatus = row.status === 1 ? 0 : 1
  
  ElMessageBox.confirm(
    `确定要${statusText}「${row.name}」菜品吗？`,
    `${statusText}菜品`,
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const res = await dishApi.updateStatus(row.id, newStatus)
      if (res.code === 1) {
        ElMessage.success(`${statusText}成功`)
        row.status = newStatus
      }
    } catch (error) {
      console.error(`${statusText}菜品失败:`, error)
      ElMessage.error(`${statusText}菜品失败`)
    }
  }).catch(() => {})
}

// 状态开关变化
const handleStatusChange = async (row) => {
  try {
    const res = await dishApi.updateStatus(row.id, row.status)
    if (res.code === 1) {
      const statusText = row.status === 1 ? '起售' : '停售'
      ElMessage.success(`${statusText}成功`)
    }
  } catch (error) {
    console.error('修改状态失败:', error)
    ElMessage.error('修改状态失败')
    // 恢复原状态
    row.status = row.status === 1 ? 0 : 1
  }
}

// 表格选择变化
const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.id)
}

// 表格行样式
const tableRowClassName = ({ row, rowIndex }) => {
  return rowIndex % 2 === 1 ? 'row-even' : 'row-odd'
}

// 页码改变
const handleCurrentChange = (val) => {
  currentPage.value = val
  getDishList()
}

// 每页条数改变
const handleSizeChange = () => {
  currentPage.value = 1
  getDishList()
}

// 页码跳转
const handleJumpPage = () => {
  const pageNum = parseInt(jumpPage.value)
  if (isNaN(pageNum) || pageNum < 1 || pageNum > Math.ceil(total.value / pageSize.value)) {
    ElMessage.warning('请输入有效的页码')
    return
  }
  currentPage.value = pageNum
  getDishList()
}

// 生命周期
onMounted(() => {
  getCategoryList()
  getDishList()
})
</script>

<style scoped>
.dish-page {
  background: #f5f7fa;
  min-height: calc(100vh - 50px);
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header .title {
  font-size: 22px;
  font-weight: bold;
  color: #333;
  margin-bottom: 8px;
}

.page-header .desc {
  font-size: 14px;
  color: #666;
}

.content-card {
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  padding: 20px;
}

.search-bar {
  margin-bottom: 20px;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}

.search-item {
  display: flex;
  align-items: center;
  margin-right: 15px;
  margin-bottom: 10px;
}

.search-input {
  width: 200px;
}

.type-select,
.status-select {
  width: 150px;
}

.search-btn {
  margin-right: 10px;
  margin-bottom: 10px;
}

.refresh-btn {
  margin-right: 10px;
  margin-bottom: 10px;
}

.add-btn {
  margin-right: 10px;
  margin-bottom: 10px;
}

.batch-delete-btn {
  margin-bottom: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

.page-size-select {
  margin: 0 10px;
  width: 100px;
}

.jump-page {
  width: 50px;
  margin: 0 5px;
}

/* 表格行样式 */
:deep(.row-even) {
  background-color: #fafafa;
}

:deep(.row-odd) {
  background-color: #fff;
}

:deep(.el-table th) {
  font-weight: bold !important;
}

:deep(.el-table th.el-table__cell) {
  background-color: #f5f7fa !important;
}

/* 操作按钮样式 */
.operation-btns {
  display: flex;
  justify-content: center;
  align-items: center;
}

.op-button {
  color: #409EFF;
  display: flex;
  align-items: center;
}

.op-button-danger {
  color: #F56C6C;
  display: flex;
  align-items: center;
}

.op-button-warning {
  color: #E6A23C;
  display: flex;
  align-items: center;
}

.op-button-success {
  color: #67C23A;
  display: flex;
  align-items: center;
}

.op-button i, 
.op-button-danger i,
.op-button-warning i,
.op-button-success i {
  margin-right: 4px;
}

/* 时间信息样式 */
.time-info {
  display: flex;
  align-items: center;
  color: #606266;
}

.time-info i {
  margin-right: 5px;
  font-size: 14px;
}

/* 菜品信息样式 */
.dish-info {
  display: flex;
  align-items: center;
}

.dish-image {
  width: 40px;
  height: 40px;
  border-radius: 4px;
  margin-right: 10px;
  object-fit: cover;
}

.dish-name {
  font-weight: 500;
}

/* 下拉菜单样式 */
:deep(.el-select-dropdown__item) {
  padding: 0 20px;
  font-size: 14px;
  color: #333;
}

:deep(.el-select-dropdown__item.selected) {
  color: #409EFF;
  font-weight: bold;
}
</style> 